/*
 * @Description:菜单controller
 * @Version: 2.0
 * @Autor: kafei
 * @Date: 2021-12-07 17:43:39
 * @LastEditors: kafei
 * @LastEditTime: 2021-12-21 15:22:05
 */
const {
  allMenuServer,
  updateMenuServer,
  getMenuByIdServer,
  addMenuServer,
  delMenuServer
} = require('../server/menuServer')
const result = require('../utils/result')
const { BfsTreeData } = require('../utils/tree')
async function allMenuController() {
  const data = await allMenuServer()
  return result('0', { data })
}

async function updateMenuController(res) {
  const data = await updateMenuServer(res)
  return result('0', { data })
}

async function getMenuByIdController(id) {
  const data = await getMenuByIdServer(id)
  return result('0', { data })
}

async function addMenuController(res) {
  delete res.id

  if (!res.parentId) {
    res.parentId = 0
  } else {
    const menuData = await allMenuServer()
    const targetMid = BfsTreeData(menuData, (item) => {
      if (item.id === res.parentId) {
        return item
      }
    }, { pId: 'parentId' })
    res.mid = targetMid.mid
  }
  const data = await addMenuServer(res)
  return result('0', { data })
}

async function delMenuController(res) {
  const data = await delMenuServer(res)
  return result('0', { data })
}

module.exports = {
  allMenuController,
  updateMenuController,
  getMenuByIdController,
  addMenuController,
  delMenuController
}
